package com.tmanager.web.listeners;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.tmanager.persistence.dao.UserDAO;
import com.tmanager.persistence.entity.User;
import com.tmanager.persistence.tx.Transactional;
import com.tmanager.utils.Crypto;

public class TestListener implements ServletContextListener {
	private static final Logger log = LoggerFactory.getLogger(TestListener.class);
	

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	@Singleton
	static class TestDataCreator {
		@Inject
		private UserDAO userDAO;
		@Transactional(rollbackOn = Exception.class)
		public void run() {
			User user = userDAO.getUserByEmail("admin@test.com");
			if (user != null) {
				return;
			}
			user = new User();
			user.setPassword(Crypto.digestSHA1("test"));
			user.setEmail("admin@test.com");
			userDAO.save(user);
		}
	}

	private Injector injector;

	@Override
	public void contextInitialized(ServletContextEvent context) {
		injector = (Injector) context.getServletContext().getAttribute(Injector.class.getName());
		if (injector == null) {
			log.error("Guice Injector not found");
			return;
		}
		injector.injectMembers(this);
		injector.getInstance(TestDataCreator.class).run();
	}

}
